<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="140px"
      v-loading="formLoading"
    >
      <el-form-item label="平台编号" prop="platformId">
        <el-input v-model="formData.platformId" placeholder="请输入平台编号" />
      </el-form-item>
      <el-form-item label="店铺编号" prop="storeId">
        <el-input v-model="formData.storeId" placeholder="请输入店铺编号" />
      </el-form-item>
      <el-form-item label="API配置编号" prop="apiConfigId">
        <el-input v-model="formData.apiConfigId" placeholder="请输入API配置编号" />
      </el-form-item>
      <el-form-item label="同步任务编号" prop="syncTaskId">
        <el-input v-model="formData.syncTaskId" placeholder="请输入同步任务编号" />
      </el-form-item>
      <el-form-item label="链路追踪编号" prop="traceId">
        <el-input v-model="formData.traceId" placeholder="请输入链路追踪编号" />
      </el-form-item>
      <el-form-item label="API类型" prop="apiType">
        <el-select v-model="formData.apiType" placeholder="请选择API类型">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.CROSSBORDER_DATA_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="API名称" prop="apiName">
        <el-input v-model="formData.apiName" placeholder="请输入API名称" />
      </el-form-item>
      <el-form-item label="API端点" prop="apiEndpoint">
        <el-input v-model="formData.apiEndpoint" placeholder="请输入API端点" />
      </el-form-item>
      <el-form-item label="HTTP方法" prop="httpMethod">
        <el-select v-model="formData.httpMethod" placeholder="请选择HTTP方法">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.CROSSBORDER_HTTP_METHOD)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="请求头" prop="requestHeaders">
        <el-input v-model="formData.requestHeaders" placeholder="请输入请求头" />
      </el-form-item>
      <el-form-item label="请求参数" prop="requestParams">
        <el-input v-model="formData.requestParams" placeholder="请输入请求参数" />
      </el-form-item>
      <el-form-item label="请求体" prop="requestBody">
        <el-input v-model="formData.requestBody" placeholder="请输入请求体" />
      </el-form-item>
      <el-form-item label="响应状态码" prop="responseStatus">
        <el-radio-group v-model="formData.responseStatus">
          <el-radio value="1">请选择字典生成</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="响应头" prop="responseHeaders">
        <el-input v-model="formData.responseHeaders" placeholder="请输入响应头" />
      </el-form-item>
      <el-form-item label="响应体" prop="responseBody">
        <el-input v-model="formData.responseBody" placeholder="请输入响应体" />
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker
          v-model="formData.startTime"
          type="date"
          value-format="x"
          placeholder="选择开始时间"
        />
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker
          v-model="formData.endTime"
          type="date"
          value-format="x"
          placeholder="选择结束时间"
        />
      </el-form-item>
      <el-form-item label="执行时长（毫秒）" prop="duration">
        <el-input v-model="formData.duration" placeholder="请输入执行时长（毫秒）" />
      </el-form-item>
      <el-form-item label="是否成功" prop="success">
        <el-select v-model="formData.success" placeholder="请选择是否成功">
          <el-option
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="String(dict.value)"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="错误代码" prop="errorCode">
        <el-input v-model="formData.errorCode" placeholder="请输入错误代码" />
      </el-form-item>
      <el-form-item label="错误信息" prop="errorMsg">
        <el-input v-model="formData.errorMsg" placeholder="请输入错误信息" />
      </el-form-item>
      <el-form-item label="重试次数" prop="retryCount">
        <el-input v-model="formData.retryCount" placeholder="请输入重试次数" />
      </el-form-item>
      <el-form-item label="用户IP" prop="userIp">
        <el-input v-model="formData.userIp" placeholder="请输入用户IP" />
      </el-form-item>
      <el-form-item label="用户代理" prop="userAgent">
        <el-input v-model="formData.userAgent" placeholder="请输入用户代理" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions, getStrDictOptions, getBoolDictOptions } from '@/utils/dict'
import { PlatformApiLogApi, PlatformApiLogVO } from '@/api/crossborder/platformapilog'

/** 跨境电商平台API调用日志 表单 */
defineOptions({ name: 'PlatformApiLogForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  platformId: undefined,
  storeId: undefined,
  apiConfigId: undefined,
  syncTaskId: undefined,
  traceId: undefined,
  apiType: undefined,
  apiName: undefined,
  apiEndpoint: undefined,
  httpMethod: undefined,
  requestHeaders: undefined,
  requestParams: undefined,
  requestBody: undefined,
  responseStatus: undefined,
  responseHeaders: undefined,
  responseBody: undefined,
  startTime: undefined,
  endTime: undefined,
  duration: undefined,
  success: undefined,
  errorCode: undefined,
  errorMsg: undefined,
  retryCount: undefined,
  userIp: undefined,
  userAgent: undefined,
})
const formRules = reactive({
  platformId: [{ required: true, message: '平台编号不能为空', trigger: 'blur' }],
  traceId: [{ required: true, message: '链路追踪编号不能为空', trigger: 'blur' }],
  apiType: [{ required: true, message: 'API类型不能为空', trigger: 'change' }],
  apiName: [{ required: true, message: 'API名称不能为空', trigger: 'blur' }],
  apiEndpoint: [{ required: true, message: 'API端点不能为空', trigger: 'blur' }],
  httpMethod: [{ required: true, message: 'HTTP方法不能为空', trigger: 'blur' }],
  startTime: [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],
  success: [{ required: true, message: '是否成功不能为空', trigger: 'blur' }],
  retryCount: [{ required: true, message: '重试次数不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await PlatformApiLogApi.getPlatformApiLog(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as PlatformApiLogVO
    if (formType.value === 'create') {
      await PlatformApiLogApi.createPlatformApiLog(data)
      message.success(t('common.createSuccess'))
    } else {
      await PlatformApiLogApi.updatePlatformApiLog(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    platformId: undefined,
    storeId: undefined,
    apiConfigId: undefined,
    syncTaskId: undefined,
    traceId: undefined,
    apiType: undefined,
    apiName: undefined,
    apiEndpoint: undefined,
    httpMethod: undefined,
    requestHeaders: undefined,
    requestParams: undefined,
    requestBody: undefined,
    responseStatus: undefined,
    responseHeaders: undefined,
    responseBody: undefined,
    startTime: undefined,
    endTime: undefined,
    duration: undefined,
    success: undefined,
    errorCode: undefined,
    errorMsg: undefined,
    retryCount: undefined,
    userIp: undefined,
    userAgent: undefined,
  }
  formRef.value?.resetFields()
}
</script>